package LeetCode刷题;

/**
 * @program: Java_Study
 * @author: Xiaofan
 * @createTime: 2021-10-04 16:28
 * @description: Functions of this class is
 * 官方题解（一遍遍历）：
 *class Solution {
 *     public ListNode removeNthFromEnd(ListNode head, int n) {
 *         ListNode dummy = new ListNode(0, head);
 *         //哨兵节点
 *         //作用它删除节点是通过把需要删除节点的前一个和后一个连接，如果不加dummy节点，
 *         那删除第一个节点就删不掉了。加了的话，可以通过dummy.next = dummy.next.next删除
 *
 *
 *         ListNode first = head;
 *         ListNode second = dummy;
 *         for (int i = 0; i < n; ++i) {
 *             first = first.next;
 *         }
 *         while (first != null) {
 *             first = first.next;
 *             second = second.next;
 *         }
 *         second.next = second.next.next;
 *         ListNode ans = dummy.next;
 *         return ans;
 *     }
 * }
 **/
public class NoNo删除倒数第n个节点 {
    public static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
    public static void main(String[] args) {

    }
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if(head!=null){
            //两边扫描实现
            int sum=0;
            ListNode h=head;
            while(h!=null){
                sum++;
                h=h.next;
            }
            n=sum-n;
            sum=0;
            if(n==0){
                return head.next;
            }
            h=head;
            while(h!=null&&h.next!=null){
                if(sum==n-1){
                    h.next=h.next.next;
                    break;
                }
                sum++;
                h=h.next;
            }

        }
        return head;
    }
}